package top.idcard.agent.biz.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.idcard.agent.biz.entity.Certification;
import top.idcard.agent.biz.rw.read.AbstractRead;
import top.idcard.agent.biz.rw.read.device.CVRNativeFunction;
import top.idcard.agent.biz.rw.read.device.FunctionResultEnum;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author wx
 * @version 1.0
 * @date 2021/2/2 11:28 上午
 */
public class CertificationReadService {

    private Logger logger = LoggerFactory.getLogger(CertificationReadService.class);

    private CVRNativeFunction cvrNativeFunction = new CVRNativeFunction();

    private AtomicBoolean listenFlag = new AtomicBoolean(false);
    private AtomicBoolean connectStatus = new AtomicBoolean(false);

    private AbstractRead deviceRead;

    public Boolean connectDevice() {
        int init = cvrNativeFunction.init();
        if (init != FunctionResultEnum.SUCCESS.getCode()) {
            connectStatus.set(false);
            logger.info("连接设备失败");
            return false;
        }
        connectStatus.set(true);
        return true;
    }

    public void startListening(){
        listenFlag.set(true);
        ConnectListen connectListen = new ConnectListen();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(connectListen);
    }

    public Boolean getStatus(){
        return connectStatus.get();
    }

    public void close(){
        listenFlag.set(false);
    }

    public Boolean init() {
        int init = cvrNativeFunction.init();
        if (init != FunctionResultEnum.SUCCESS.getCode()) {
            return true;
        }
        return false;
    }

    public Certification readFromDevice(){
//        abstractLocalFileRead.
        return null;
    }

    class ConnectListen implements Runnable {

        @Override
        public void run() {
            while (listenFlag.get()) {
                try {
                    if (getConnectStatus()) {
                        connectStatus.set(true);
                        logger.info("设备连接正常");
                        Thread.sleep(2500L);
                    } else {
//                        connectDevice();
                        connectStatus.set(false);
                        logger.warn("未连接到读卡器！！！");
                        Thread.sleep(1500L);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        private Boolean getConnectStatus(){
            int status = cvrNativeFunction.getStatus();
            if(status != FunctionResultEnum.STATUS_NORMAL.getCode()){
                return false;
            }
            return true;
        }
    }
}
